package top.tocchen.bookshop.controller;

import top.tocchen.bookshop.util.GetAllPrice;
import top.tocchen.bookshop.entity.CartEntity;
import top.tocchen.bookshop.entity.CartDoEntity;
import top.tocchen.bookshop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author tocchen
 * @date 2022/8/9 19:34
 * @since jdk 1.8
 **/
@Controller
public class CartController {
    @Autowired
    CartService cartService;
    @RequestMapping("/cart")
    public String goCart(HttpSession session, ModelMap map){
        String user = (String)session.getAttribute("user_name");
        Integer uid = (Integer)session.getAttribute("user_id");
        if(user==null||user==""){
            return "login";
        }
        List<CartDoEntity> cartDos = cartService.findByCartUserId(uid);
        map.addAttribute("carts",cartDos);
        map.addAttribute("allprice", GetAllPrice.getAllPrice(cartDos));
        map.addAttribute("itemsTotal",cartDos.size());
       return "cart";
    }

    @RequestMapping("/cart/add")
    @ResponseBody
    public String addCart(CartEntity cart, HttpSession session){
        if (session.getAttribute("user_name")==null||session.getAttribute("user_name")==""){
            return "250";
        }
        int uid = (int)session.getAttribute("user_id");
        cart.setUid(uid);
        cartService.insert(cart);
        return "300";
    }
    @RequestMapping("/cart/update")
    @ResponseBody
    public String addCart(@RequestParam("cartid") int cartid,@RequestParam("bookNum") int count, HttpSession session){
        CartEntity c = new CartEntity();
        c.setId(cartid);
        c.setCount(count);
        cartService.updateByIdSetCount(c);
        return "300";
    }
}
